package org.example.rubbish.mapper;

import org.apache.ibatis.annotations.*;
import org.example.rubbish.entity.AdminUser;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Mapper
public interface AdminUserMapper {

    @Select("SELECT id, username, password, salt, real_name, role, status, department, permissions, create_time, update_time, last_login_ip, last_login_time FROM admin_user WHERE username = #{username} AND status = 1")
    Optional<AdminUser> selectByUsername(String username);

    @Select("SELECT id, username, password, salt, real_name, role, status, department, permissions, create_time, update_time, last_login_ip, last_login_time FROM admin_user WHERE id = #{id}")
    Optional<AdminUser> selectById(Long id);

    @Insert("INSERT INTO admin_user(username, password, salt, real_name, role, status, department, permissions, create_time, update_time) " +
            "VALUES(#{username}, #{password}, #{salt}, #{realName}, #{role}, #{status}, #{department}, #{permissions}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(AdminUser adminUser);

    @Update("UPDATE admin_user SET password = #{password}, update_time = #{updateTime} WHERE id = #{id}")
    int updatePassword(@Param("id") Long id, @Param("password") String password, @Param("updateTime") Date updateTime);

    @Update("UPDATE admin_user SET last_login_ip = #{lastLoginIp}, last_login_time = #{lastLoginTime}, update_time = #{lastLoginTime} WHERE id = #{id}")
    int updateLoginInfo(@Param("id") Long id, @Param("lastLoginIp") String lastLoginIp, @Param("lastLoginTime") Date lastLoginTime);

    @Select("SELECT id, username, real_name, role, status, department, permissions, create_time, update_time, last_login_ip, last_login_time FROM admin_user WHERE status = 1 ORDER BY create_time DESC")
    List<AdminUser> selectAll();


    @Update("UPDATE admin_user SET status = #{status}, update_time = #{updateTime} WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") Integer status, @Param("updateTime") Date updateTime);

    @Update("UPDATE admin_user SET status = 0, update_time = #{updateTime} WHERE id = #{id}")
    int softDeleteById(@Param("id") Long id, @Param("updateTime") Date updateTime);

    @Update("UPDATE admin_user SET username = #{username}, real_name = #{realName}, role = #{role}, " +
            "department = #{department}, permissions = #{permissions}, update_time = #{updateTime} " +
            "WHERE id = #{id}")
    int update(AdminUser adminUser);

    @Select("SELECT COUNT(*) FROM admin_user WHERE username = #{username} AND id != #{id}")
    int countByUsernameExcludingId(@Param("username") String username, @Param("id") Long id);
}